
package com.example.sunsg.okhttptest.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.util.HashMap;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.os.StatFs;
import android.text.TextUtils;
import android.util.Log;

import com.example.sunsg.okhttptest.TheApplication;

public class StorageUtils {

	public static final String SDCARD_ROOT = Environment.getExternalStorageDirectory().getAbsolutePath() + "/";
    public static final String FILE_ROOT = SDCARD_ROOT + "sunsg";
    public static final long LOW_STORAGE_THRESHOLD = 1024 * 1024 * 10;

    /**
     * sdcard 是否可写
     * @return
     */
    public static boolean isSdCardWrittenable() {

        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            return true;
        }
        return false;
    }
    /**
     * 获得sdcard的存储空间
     * @return
     */
    public static long getAvailableStorage() {
        String storageDirectory = null;
        storageDirectory = Environment.getExternalStorageDirectory().toString();
        try {
            StatFs stat = new StatFs(storageDirectory);
            long avaliableSize = ((long) stat.getAvailableBlocks() * (long) stat.getBlockSize());
            return avaliableSize;
        } catch (RuntimeException ex) {
            return 0;
        }
    }

    /**
     * 判断sdcard是否大于 10M
     * @return
     */
    public static boolean checkAvailableStorage() {
        if (getAvailableStorage() < LOW_STORAGE_THRESHOLD) {
            return false;
        }
        return true;
    }

    public static boolean isSDCardPresent() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }
    /**
     * 创建sunsg 目录
     * @throws IOException
     */
    public static String mkdir(){
        String path = "";
        try{
            File file = new File(FILE_ROOT);
            if (!file.exists() || !file.isDirectory())
                file.mkdirs();
            path = file.getAbsolutePath();
        }catch (Exception equals){

        }

        return path;
    }

    /**
     * 获取文件的大小单位
     * @param filePath
     * @return
     */
    public static String getFileSize(String filePath){
        String size = "";
        File file = new File(filePath);
        if(file.exists()){
            size = size(file.length());
        }
        return size;
    }


    /**
     * 转换成可度单位
     * @param size
     * @return
     */
    public static String size(long size) {
        if (size / (1024 * 1024) > 0) {
            float tmpSize = (float) (size) / (float) (1024 * 1024);
            DecimalFormat df = new DecimalFormat("#.##");
            return "" + df.format(tmpSize) + "MB";
        } else if (size / 1024 > 0) {
            return "" + (size / (1024)) + "KB";
        } else
            return "" + size + "B";
    }

    /**
     * 删除目录文件
     * @param path
     * @return
     */
    public static boolean delete(File path) {
        boolean result = true;
        if (path.exists()) {
            if (path.isDirectory()) {
                for (File child : path.listFiles()) {
                    result &= delete(child);
                }
                result &= path.delete(); // Delete empty directory.
            }
            if (path.isFile()) {
                result &= path.delete();
            }
            if (!result) {
                Log.e(null, "Delete failed;");
            }
            return result;
        } else {
            Log.e(null, "File does not exist.");
            return false;
        }
    }

    /**
     * copy文件
     * @param fromFile 原文件
     * @param toFilePath 目标文件目录
     * @return
     */
    
    public static void copyFile(File fromFile,String toFilePath){
    	File toFile = new File(toFilePath);

        try {
        	if(!toFile.exists()){
        		FileInputStream fis = new FileInputStream(fromFile);
                writeFile(fis, toFilePath);
        	}
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    }
    /**
     * copy文件
     * @param inputStream
     * @return
     */
    public static void writeFile(InputStream inputStream ,String toFilePath){
    		File toFile = new File(toFilePath);
        	try {
        		if(!toFile.exists()){
        			FileOutputStream fos = new FileOutputStream(toFile);
        			byte[] buffer = new byte[1024];
        			int length = 0;
        			while((length = inputStream.read(buffer))!=-1){
        				fos.write(buffer,0,length);
        			}
        			fos.flush();
        			fos.close();
        			inputStream.close();
        		}
    			
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    }

    /**
     * 一行行 读取文件
     * @param filename
     */
    public void readLineFile(String filename){
        try {
            FileInputStream in = new FileInputStream(filename);
            InputStreamReader inReader = new InputStreamReader(in, "UTF-8");
            BufferedReader bufReader = new BufferedReader(inReader);
            String line = null;
            int i = 1;
            while((line = bufReader.readLine()) != null){
                System.out.println("第" + i + "行：" + line);
                i++;
            }
            bufReader.close();
            inReader.close();
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("读取" + filename + "出错！");
        }
    }

    /**
     * 一行行写入文件
     * @param filename
     * @param content
     */
    public void writeLineFile(String filename, String[] content){
        try {
            FileOutputStream out = new FileOutputStream(filename);
            OutputStreamWriter outWriter = new OutputStreamWriter(out, "UTF-8");
            BufferedWriter bufWrite = new BufferedWriter(outWriter);
            for (int i = 0; i < content.length; i++) {
                bufWrite.write(content[i] + "\r\n");
            }
            bufWrite.close();
            outWriter.close();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("读取" + filename + "出错！");
        }
    }

    /**
     * 读取一行 根据规则写入一样
     *
     * "file:///android_asset/文件名"
     * @param fromFile
     * @param toFile
     */
    public static void readAndWriteLine(String fromFile,String toFile){
        try {
            //读取
//            FileInputStream in = new FileInputStream(fromFile);
            InputStream in = TheApplication.getApplication().getAssets().open("russa");
            InputStreamReader inReader = new InputStreamReader(in, "UTF-8");
            BufferedReader bufReader = new BufferedReader(inReader);
            String line = null;

            //写入
            FileOutputStream out = new FileOutputStream(toFile);
            OutputStreamWriter outWriter = new OutputStreamWriter(out, "UTF-8");
            BufferedWriter bufWrite = new BufferedWriter(outWriter);

            int i = 1;
            while((line = bufReader.readLine()) != null){
                Log.i("test","第" + i + "行：" + line);
                bufWrite.write(getStringXmlStyle(line));
                i++;
            }
            bufReader.close();
            inReader.close();
            in.close();

            bufWrite.close();
            outWriter.close();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
//            System.out.println("读取" + fromFile + "出错！");
        }
    }

    public static String getStringXmlStyle(String line){
        String[] array = line.split("###");
        StringBuilder builder = new StringBuilder();
        if(array.length >=3){
            if(!TextUtils.isEmpty(array[0])){
                builder.append("<string name=\"");
                builder.append(array[0]);//key
                builder.append("\">");
                builder.append(array[2]);//value
                builder.append("</string>");
                builder.append("<!--");
                builder.append(array[1]);
                builder.append("-->");
                builder.append("\r\n");
            }
        }
//         if(array.length ==2){
//            if(!TextUtils.isEmpty(array[0])){
//                builder.append("<string name=\"");
//                builder.append(array[0]);//key
//                builder.append("\">");
//                builder.append(array[1]);//value
//                builder.append("</string>");
//                builder.append("<!--");
//                builder.append(array[1]);
//                builder.append("-->");
//                builder.append("\r\n");
//            }
//        }
        return builder.toString();

    }


}
